package docsync.doclist;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

public class ClientLogin {
	// String accountType;
	String Email;
	String Passwd;
	String authToken;
	String service;

	public ClientLogin(String Em, String pwd, String service) {
		this.Email = Em;
		this.Passwd = pwd;
		this.service = service;
	}

	public void login() throws Exception {

		HttpClient client = new DefaultHttpClient();
		String postURL = "https://www.google.com/accounts/ClientLogin";
		HttpPost post = new HttpPost(postURL);
		// System.out.println("Post is " + post.toString());
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		nvps.add(new BasicNameValuePair("accountType", "HOSTED_OR_GOOGLE"));
		nvps.add(new BasicNameValuePair("Email", this.Email));
		nvps.add(new BasicNameValuePair("Passwd", this.Passwd));
		nvps.add(new BasicNameValuePair("service", this.service));// this key
		// must be
		// in
		// lowercase

		UrlEncodedFormEntity uent = new UrlEncodedFormEntity(nvps, HTTP.UTF_8);
		// System.out.println("URL encoded entity " + uent.toString());
		post.setEntity(uent);
		HttpResponse response = client.execute(post);
		// System.out.println("Response is " + response.getStatusLine());
		if (response.getStatusLine().getStatusCode() != 200)
			throw new Exception("Login Failed");
		HttpEntity hent = response.getEntity();
		assert (hent != null);
		// System.out.println("Http Response Entity " + hent);

		String resp = EntityUtils.toString(hent);
		String prefix = "Auth=";
		int s = resp.indexOf(prefix);
		// System.out.println( s );
		int e = resp.indexOf('\n', s);
		// System.out.println( e );
		authToken = resp.substring(s + prefix.length(), e);
		// System.out.println(authToken);

	}

	public String getAuthToken() {
		return authToken;
	}

}